package com.wisedu.pdf.service;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.servlet.http.Part;

import com.nway.pdf.Word2Pdf;

public class Word2PdfService {

	public String convert(Part docFile, String tmpFile) {

		int status = 0;
		File doc = new File(tmpFile, docFile.getSubmittedFileName());
		
		String wordPath = doc.getAbsolutePath();
		String pdfPath = wordPath.substring(0, wordPath.lastIndexOf('.') + 1) + "pdf";

		try 
		{
			copy(docFile.getInputStream(), new FileOutputStream(doc));

			status = Word2Pdf.convert(wordPath, pdfPath);
		} 
		catch (Throwable e)
		{
			e.printStackTrace();
		} 
		finally 
		{
			doc.delete();
		}

		return status == 1 ? pdfPath : null;
	}
	
	public void copy(InputStream is, OutputStream os) throws IOException {

		byte[] readData = new byte[2048];

		try {
			
			int dataLength = is.read(readData);

			while (dataLength != -1) {

				os.write(readData, 0, dataLength);
				dataLength = is.read(readData);
			}
			
		} 
		catch (IOException e) 
		{
			throw e;
		} 
		finally 
		{
			is.close();
			os.close();
		}
	}
	
	public void write(String file, OutputStream os) throws IOException {

		File pdfFile = new File(file);

		try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(pdfFile))) 
		{
			copy(bis, os);
		} 
		catch (IOException e) 
		{
			throw e;
		} 
		finally 
		{
			pdfFile.delete();
		}
	}

}
